package com.atguigu.gulimall.order.intercepter;

import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.vo.MemberOAuthVo;
import org.apache.shiro.util.AntPathMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class OrderLoginIntercepter implements HandlerInterceptor {

    public static ThreadLocal<MemberOAuthVo> threadLocal = new ThreadLocal<>();

    /**
     *  用户必须登录才能访问order服务
     *  如果用户未登录去访问结算页就拦截，跳转至登录页面
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行ware库存服务查订单
        String requestURI = request.getRequestURI();
        boolean matches = new AntPathMatcher().matches("/order/order/status/**", requestURI);
        if (matches){
            return true;
        }


        MemberOAuthVo attribute = (MemberOAuthVo)request.getSession().getAttribute(AuthServiceConstant.LOGIN_USER);
        if (attribute != null){
            threadLocal.set(attribute);
            return true;
        }else {
            //跳转至登录页面
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }

}
